package com.clsz.service.impl;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.clsz.service.SMSService;
import com.clsz.utils.AliSMSClient;
import com.clsz.utils.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SMSServiceImpl implements SMSService {
    @Resource
    private AliSMSClient aliSMSClient;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean sendSMSValidate(String phone) {
        Integer code = (int) (Math.random() * (100000 - 10000)+100000);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName("学掌门超全栈开发");
        request.setTemplateCode("SMS_243437190");
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        SendSmsResponse res = null;
        try {
            res = aliSMSClient.createClient().sendSmsWithOptions(request, new RuntimeOptions());
            if ("OK".equalsIgnoreCase(res.getBody().getCode())) {
                //存储验证码
                /*
                request请求作用域
                session会话作用域
                servletContext
                文件系统
                SQL数据库
                nosql
                 */
                String key ="SMS-Validate-"+phone;
                redisUtils.set(key, code,30*60);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
